<?php

namespace App\Http\Middleware;

use Closure;

class ValidatorSign
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->validatorSign($request->all());
        return $next($request);
    }

    function validatorSign($request)
    {
        $sign=@$request['sign'];
        $timestamp=@$request['timestamp'];
        $noncestr=@$request['noncestr'];
        if(!$sign || !$timestamp || !$noncestr)
        {
            echo json_encode(Array(
                'status'=>'failed',
                'message'=>'签名验证错误!',
            ));
            exit;
        }
        $request=$this->paraFilter($request);
        $request=$this->argSort($request);
        if($sign<>md5($this->createLinkstring($request))) {
            echo json_encode(Array(
                'status' => 'failed',
                'message' => '签名验证错误!',
            ));
            exit;
        }
    }

    function createLinkstring($para) {
        $arg  = "";
        while (list ($key, $val) = each ($para)) {
            $arg.=$key."=".$val."&";
        }
        //去掉最后一个&字符
//        $arg = substr($arg,0,count($arg)-2);
        $arg=$arg . "salt=" . env('APP_SALT');
        return $arg;
    }

    function paraFilter($para) {
        $para_filter = array();
        while (list ($key, $val) = each ($para)) {
            if($key == "sign" || $key == "sign_type" || $val == "")continue;
            else	$para_filter[$key] = $para[$key];
        }
        return $para_filter;
    }

    function argSort($para) {
        ksort($para);
        reset($para);
        return $para;
    }
}
